import 'package:flutter/material.dart';
import 'cardDetail.dart';
import 'Util.dart';
import 'dart:io';
import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'package:barcode_scan/barcode_scan.dart';
import 'package:shared_preferences/shared_preferences.dart';

class CardPage extends StatefulWidget {
  CardPage({Key key, this.title, this.para}) : super(key: key);
  final String title;
  final Map<String, dynamic> para;
  @override
  _CardPage createState() => _CardPage();
}

class _CardPage extends State<CardPage> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    print(widget.para.toString());
    loadData();
  }
  loadData() {
    SharedPreferences.getInstance().then((value){
      setState(() {
        String domain = value.getString("buildings").toMap()["subdomain"].toString();
        print(domain);
        var dic = widget.para;
        dic["api_key"] = "xQITe6bZFUrmeJbkcKgkUzajUI6FGLA";
        dic["lang"] = "en";
        print(dic);
        var dio = Dio();
        if (ShareHandle.instance.proxy.length > 0){
          (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (HttpClient client){
            client.findProxy = (uri) {
              return ShareHandle.instance.proxy;
            };
          };
        }
        dio.post("${domain}/api/staff/duty_list",data:FormData.fromMap(dic)).then((response){
          final result = response.toResult();
          print(result.item1);
          if (result.item2){
            setState(() {
              this.dataList = List<Map<String, dynamic>>.from(result.item1["container"] ?? []);
            });
          }else{
            showAlert(result.item4);
          }
        }).catchError((error){
          print("error:${error}");
          showAlert(error.toString());
        });
      });
    });
  }
  /// 实际上的真正跳转
  realLoad(qr) {

    String block_key = widget.para["block_key"];
    Map<String,String> dic = {"api_key":"xQITe6bZFUrmeJbkcKgkUzajUI6FGLA","block_key":block_key,"lang":"en","staff_key":qr};
    var dio = Dio();
    if (ShareHandle.instance.proxy.length > 0){
      (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (HttpClient client){
        client.findProxy = (uri) {
          return ShareHandle.instance.proxy;
        };
      };
    }
    SharedPreferences.getInstance().then((value) {
      String domain = value.getString("buildings").toMap()["subdomain"]
          .toString();
      dio.post("http://${domain}/api/staff/duty",data:FormData.fromMap(dic)).then((value){
        print(value.toString());
        final result = value.toResult();
        if (result.item2){
          var _dic = this.widget.para;
          _dic["staff"] = result.item1;
        }
      });
    });
  }

  Future scan() async {
    if (ShareHandle.instance.shouldUseCamara){

      var result = await BarcodeScanner.scan();
      if (result.type == ResultType.Barcode) {
        showDialog<Null>(
            context: context,
            barrierDismissible: false,
            builder: (BuildContext context) {
              return new AlertDialog(
                title: new Text(result.rawContent),
                //可滑动
                content: new SingleChildScrollView(
                  child: new ListBody(
                    children: <Widget>[
                      new Text(''),
                    ],
                  ),
                ),
                actions: <Widget>[
                  new FlatButton(
                    child: new Text('确定'),
                    onPressed: () {
                      Navigator.of(context).pop();
                      realLoad(result.rawContent);
                    },
                  ),
                  new FlatButton(
                    child: new Text('取消'),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                ],
              );
            });
      }

      print(result.type); // The result type (barcode, cancelled, failed)
      print(result.rawContent); // The barcode content
      print(result.format); // The barcode format (as enum)
      print(result
          .formatNote); // If a unknown format was scanned this field contains a note
    }else{
      realLoad("wgEWKqHbRE3fIMeyHg");
    }
  }
  List<Map<String, dynamic>> dataList = [];
  @override
  Widget build(BuildContext context) {
    List<Row> cards = [];
    for (var v in dataList) {
      Row card = Row(
        children: <Widget>[
          SizedBox(width: 20,),
          Image(
            image: AssetImage("assets/images/icon_passport.png"),
          ),
          SizedBox(width: 20,),
          Text("${v["staff_name"]}(職員編號: ${v["staff_code"]})",style: TextStyle(fontWeight: FontWeight.bold),),
        ],
      );
      cards.add(card);
    }
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
          actions: <Widget>[
            FlatButton(
              child: Text("登出",style: TextStyle(color: Colors.white),),
              onPressed: () {
                Navigator.of(context).popUntil((route) => route.settings.name == "MyHome2Page");
              },
            )
          ]
      ),
      body: Column(
        children: <Widget>[
          Text("當值職員:",style: TextStyle(color: Color(0xff006fb2),fontWeight: FontWeight.bold,fontSize: 21),),
          SizedBox(
            height: 20,
          ),
          Expanded(
            child: ListView(children: cards),
          ),
          Row(
            children: <Widget>[
              Align(
                alignment: Alignment.centerLeft,
                child: FlatButton(
                  onPressed: () {
                  },
                  child: Stack(
                    alignment: Alignment.center,
                    children: <Widget>[
                      Image(
                        image: AssetImage(
                            "assets/images/btn_bg_scan-_qr.png"),
                      ),
                      Text(
                        "掃描更多工作證",
                        style: new TextStyle(
                            color: Color.fromARGB(255, 255, 255, 255),
                            fontSize: 18),
                      )
                    ],
                  ),
                )
              ),
              Align(
                alignment: Alignment.centerLeft,
                child: MaterialButton(
                  materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  height: 40,
                  minWidth: 200,
                  padding: EdgeInsets.all(0),
                  color: Color(0xff4a701e),
                  textColor: Colors.white,
                  shape: RoundedRectangleBorder(
                      borderRadius:
                      BorderRadius.all(Radius.circular(10))),
                  onPressed: () {
                    var dic = widget.para;
                    Navigator.push( context, MaterialPageRoute(builder: (context) => CardDetailPage(title: widget.title,para: dic,cardList: this.dataList,)),);
                  },
                  child: Text("完成掃描"),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
